package com.zenithmind.document.pojo.dto;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;

/**
 * 文档标签更新DTO
 * 遵循单一职责原则：专注于标签更新数据传输
 * 遵循开闭原则：支持字段的扩展
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Data
@Schema(description = "文档标签更新DTO")
public class DocumentTagUpdateDTO {

    @Schema(description = "标签名称", example = "Java编程")
    @Size(min = 1, max = 50, message = "标签名称长度必须在1-50字符之间")
    @Pattern(regexp = "^[\\u4e00-\\u9fa5a-zA-Z0-9_\\-\\.\\s]+$", message = "标签名称只能包含中文、英文、数字、下划线、连字符、点号和空格")
    private String name;

    @Schema(description = "标签描述", example = "Java编程语言相关文档，包含基础和高级内容")
    @Size(max = 500, message = "标签描述不能超过500字符")
    private String description;

    @Schema(description = "标签颜色", example = "#FF5722")
    @Pattern(regexp = "^#[0-9A-Fa-f]{6}$", message = "标签颜色必须是有效的十六进制颜色值")
    private String color;

    @Schema(description = "标签图标", example = "fa-java")
    @Size(max = 100, message = "标签图标不能超过100字符")
    private String icon;

    @Schema(description = "标签分类", example = "编程语言")
    @Size(max = 100, message = "标签分类不能超过100字符")
    private String category;

    @Schema(description = "父标签ID", example = "tag123456")
    private String parentTagId;

    @Schema(description = "标签级别", example = "2")
    private Integer level;

    @Schema(description = "排序权重", example = "150")
    private Integer sortWeight;

    @Schema(description = "是否系统标签", example = "false")
    private Boolean isSystemTag;

    @Schema(description = "是否公开标签", example = "true")
    private Boolean isPublic;

    @Schema(description = "是否推荐标签", example = "true")
    private Boolean isRecommended;

    @Schema(description = "是否热门标签", example = "true")
    private Boolean isHot;

    @Schema(description = "标签别名", example = "java,JAVA,Java语言,爪哇")
    private String aliases;

    @Schema(description = "相关关键词", example = "编程,开发,后端,面向对象")
    private String keywords;

    @Schema(description = "标签权重", example = "1.2")
    private Double weight;

    @Schema(description = "使用限制", example = "{\"maxUsage\": 2000, \"userLevel\": \"advanced\"}")
    private String usageRestrictions;

    @Schema(description = "标签规则", example = "{\"autoApply\": true, \"conditions\": [\"title contains java\", \"content contains 编程\"]}")
    private String tagRules;

    @Schema(description = "语言代码", example = "zh-CN")
    private String languageCode;

    @Schema(description = "地域代码", example = "CN")
    private String regionCode;

    @Schema(description = "标签状态", example = "ACTIVE", allowableValues = {"ACTIVE", "INACTIVE", "PENDING", "DEPRECATED"})
    private String status;

    @Schema(description = "扩展属性", example = "{\"difficulty\": \"intermediate\", \"popularity\": \"very_high\"}")
    private String extendedProperties;

    @Schema(description = "备注", example = "标签更新：增加了更多别名和关键词")
    private String remarks;

    @Schema(description = "更新人ID", example = "user123456")
    private String updaterId;

    @Schema(description = "更新原因", example = "用户反馈需要更准确的标签描述")
    private String updateReason;

    @Schema(description = "版本号", example = "2")
    private Integer version;

    @Schema(description = "是否启用", example = "true")
    private Boolean isEnabled;

    @Schema(description = "审核状态", example = "APPROVED", allowableValues = {"PENDING", "APPROVED", "REJECTED"})
    private String reviewStatus;

    @Schema(description = "审核意见", example = "标签更新合理，已批准")
    private String reviewComment;

    /**
     * 验证更新数据
     */
    public boolean isValid() {
        // 验证标签名称
        if (name != null) {
            if (name.trim().isEmpty() || name.length() > 50) return false;
            if (!name.matches("^[\\u4e00-\\u9fa5a-zA-Z0-9_\\-\\.\\s]+$")) return false;
        }
        
        // 验证描述长度
        if (description != null && description.length() > 500) return false;
        
        // 验证颜色格式
        if (color != null && !color.matches("^#[0-9A-Fa-f]{6}$")) return false;
        
        // 验证图标长度
        if (icon != null && icon.length() > 100) return false;
        
        // 验证分类长度
        if (category != null && category.length() > 100) return false;
        
        // 验证级别范围
        if (level != null && (level < 1 || level > 10)) return false;
        
        // 验证权重范围
        if (weight != null && (weight < 0.1 || weight > 10.0)) return false;
        
        // 验证排序权重范围
        if (sortWeight != null && (sortWeight < 0 || sortWeight > 1000)) return false;
        
        return true;
    }

    /**
     * 是否有名称更新
     */
    public boolean hasNameUpdate() {
        return name != null && !name.trim().isEmpty();
    }

    /**
     * 是否有描述更新
     */
    public boolean hasDescriptionUpdate() {
        return description != null;
    }

    /**
     * 是否有外观更新
     */
    public boolean hasAppearanceUpdate() {
        return color != null || icon != null;
    }

    /**
     * 是否有分类更新
     */
    public boolean hasCategoryUpdate() {
        return category != null;
    }

    /**
     * 是否有层级更新
     */
    public boolean hasHierarchyUpdate() {
        return parentTagId != null || level != null;
    }

    /**
     * 是否有权重更新
     */
    public boolean hasWeightUpdate() {
        return weight != null || sortWeight != null;
    }

    /**
     * 是否有状态更新
     */
    public boolean hasStatusUpdate() {
        return status != null || isEnabled != null || reviewStatus != null;
    }

    /**
     * 是否有属性更新
     */
    public boolean hasPropertyUpdate() {
        return isSystemTag != null || isPublic != null || 
               isRecommended != null || isHot != null;
    }

    /**
     * 是否有内容更新
     */
    public boolean hasContentUpdate() {
        return aliases != null || keywords != null || 
               usageRestrictions != null || tagRules != null;
    }

    /**
     * 是否有地域更新
     */
    public boolean hasLocaleUpdate() {
        return languageCode != null || regionCode != null;
    }

    /**
     * 获取别名列表
     */
    public String[] getAliasArray() {
        if (aliases == null || aliases.trim().isEmpty()) {
            return new String[0];
        }
        return aliases.split(",");
    }

    /**
     * 获取关键词列表
     */
    public String[] getKeywordArray() {
        if (keywords == null || keywords.trim().isEmpty()) {
            return new String[0];
        }
        return keywords.split(",");
    }

    /**
     * 获取更新摘要
     */
    public String getUpdateSummary() {
        StringBuilder summary = new StringBuilder();
        
        if (hasNameUpdate()) {
            summary.append("名称: ").append(name).append("; ");
        }
        
        if (hasDescriptionUpdate()) {
            summary.append("描述已更新; ");
        }
        
        if (hasAppearanceUpdate()) {
            summary.append("外观已更新; ");
        }
        
        if (hasCategoryUpdate()) {
            summary.append("分类: ").append(category).append("; ");
        }
        
        if (hasHierarchyUpdate()) {
            summary.append("层级结构已更新; ");
        }
        
        if (hasWeightUpdate()) {
            summary.append("权重已调整; ");
        }
        
        if (hasStatusUpdate()) {
            summary.append("状态已更新; ");
        }
        
        if (hasPropertyUpdate()) {
            summary.append("属性已更新; ");
        }
        
        if (hasContentUpdate()) {
            summary.append("内容已更新; ");
        }
        
        return summary.length() > 0 ? summary.toString() : "无更新";
    }

    /**
     * 创建名称更新
     */
    public static DocumentTagUpdateDTO createNameUpdate(String newName, String updaterId, String reason) {
        DocumentTagUpdateDTO dto = new DocumentTagUpdateDTO();
        dto.setName(newName);
        dto.setUpdaterId(updaterId);
        dto.setUpdateReason(reason);
        return dto;
    }

    /**
     * 创建描述更新
     */
    public static DocumentTagUpdateDTO createDescriptionUpdate(String newDescription, String updaterId, String reason) {
        DocumentTagUpdateDTO dto = new DocumentTagUpdateDTO();
        dto.setDescription(newDescription);
        dto.setUpdaterId(updaterId);
        dto.setUpdateReason(reason);
        return dto;
    }

    /**
     * 创建外观更新
     */
    public static DocumentTagUpdateDTO createAppearanceUpdate(String newColor, String newIcon, String updaterId, String reason) {
        DocumentTagUpdateDTO dto = new DocumentTagUpdateDTO();
        dto.setColor(newColor);
        dto.setIcon(newIcon);
        dto.setUpdaterId(updaterId);
        dto.setUpdateReason(reason);
        return dto;
    }

    /**
     * 创建状态更新
     */
    public static DocumentTagUpdateDTO createStatusUpdate(String newStatus, String updaterId, String reason) {
        DocumentTagUpdateDTO dto = new DocumentTagUpdateDTO();
        dto.setStatus(newStatus);
        dto.setUpdaterId(updaterId);
        dto.setUpdateReason(reason);
        return dto;
    }

    /**
     * 创建热门标签设置
     */
    public static DocumentTagUpdateDTO createHotTagUpdate(Boolean isHot, String updaterId, String reason) {
        DocumentTagUpdateDTO dto = new DocumentTagUpdateDTO();
        dto.setIsHot(isHot);
        dto.setIsRecommended(isHot);
        if (isHot) {
            dto.setSortWeight(300);
            dto.setWeight(1.2);
        }
        dto.setUpdaterId(updaterId);
        dto.setUpdateReason(reason);
        return dto;
    }

    /**
     * 创建推荐标签设置
     */
    public static DocumentTagUpdateDTO createRecommendedUpdate(Boolean isRecommended, String updaterId, String reason) {
        DocumentTagUpdateDTO dto = new DocumentTagUpdateDTO();
        dto.setIsRecommended(isRecommended);
        if (isRecommended) {
            dto.setSortWeight(200);
        }
        dto.setUpdaterId(updaterId);
        dto.setUpdateReason(reason);
        return dto;
    }

    /**
     * 创建权重调整
     */
    public static DocumentTagUpdateDTO createWeightUpdate(Double newWeight, Integer newSortWeight, String updaterId, String reason) {
        DocumentTagUpdateDTO dto = new DocumentTagUpdateDTO();
        dto.setWeight(newWeight);
        dto.setSortWeight(newSortWeight);
        dto.setUpdaterId(updaterId);
        dto.setUpdateReason(reason);
        return dto;
    }

    /**
     * 创建别名更新
     */
    public static DocumentTagUpdateDTO createAliasUpdate(String newAliases, String updaterId, String reason) {
        DocumentTagUpdateDTO dto = new DocumentTagUpdateDTO();
        dto.setAliases(newAliases);
        dto.setUpdaterId(updaterId);
        dto.setUpdateReason(reason);
        return dto;
    }

    /**
     * 创建关键词更新
     */
    public static DocumentTagUpdateDTO createKeywordUpdate(String newKeywords, String updaterId, String reason) {
        DocumentTagUpdateDTO dto = new DocumentTagUpdateDTO();
        dto.setKeywords(newKeywords);
        dto.setUpdaterId(updaterId);
        dto.setUpdateReason(reason);
        return dto;
    }

    /**
     * 创建审核更新
     */
    public static DocumentTagUpdateDTO createReviewUpdate(String reviewStatus, String reviewComment, String updaterId) {
        DocumentTagUpdateDTO dto = new DocumentTagUpdateDTO();
        dto.setReviewStatus(reviewStatus);
        dto.setReviewComment(reviewComment);
        dto.setUpdaterId(updaterId);
        dto.setUpdateReason("审核处理");
        return dto;
    }

    /**
     * 是否为重要更新
     */
    public boolean isSignificantUpdate() {
        return hasNameUpdate() || hasCategoryUpdate() || hasHierarchyUpdate() || hasStatusUpdate();
    }

    /**
     * 是否需要审核
     */
    public boolean needsReview() {
        return hasNameUpdate() || hasCategoryUpdate() || hasHierarchyUpdate();
    }

    /**
     * 计算更新重要性分数
     */
    public double calculateUpdateImportance() {
        double score = 0.0;
        
        // 名称更新权重最高 40%
        if (hasNameUpdate()) score += 0.4;
        
        // 分类更新权重 25%
        if (hasCategoryUpdate()) score += 0.25;
        
        // 层级更新权重 20%
        if (hasHierarchyUpdate()) score += 0.2;
        
        // 状态更新权重 10%
        if (hasStatusUpdate()) score += 0.1;
        
        // 其他更新权重 5%
        if (hasDescriptionUpdate() || hasAppearanceUpdate() || hasContentUpdate()) score += 0.05;
        
        return Math.min(score, 1.0);
    }
}
